<?php

namespace App\Http\Controllers\Export;

use App\Http\Controllers\Admin\CommonController;
use App\Http\Controllers\Controller;
use App\Models\AnswerActivity;
use App\Models\AnswerActivityRanking;
use App\Models\AnswerActivityUnit;
use App\Models\AnswerActivityUserUnit;
use App\Models\UserAddress;
use App\Models\UserDrawAddress;
use App\Models\UserInfo;
use App\Validate\AnswerActivityRankingValidate;
use Illuminate\Support\Facades\Cache;
use Maatwebsite\Excel\Facades\Excel;


/**
 * excel导出导入功能 
 */
class AnswerActivityRankingExport extends Controller
{

    public $model = null;
    public $activityModel = null;
    public $validate = null;
    public function __construct()
    {
        parent::__construct();

        $this->model = new AnswerActivityRanking();
        $this->activityModel = new AnswerActivity();
        $this->validate = new AnswerActivityRankingValidate();
    }

    /**
     * 活动排名导出
     * @param act_id int 活动id
     * @param unit_id int 单位id  除独立活动外，若传了则是单位排名，不传则是总排名  ；独立活动，单位排名等于独立排名
     * @param keywords int 检索条件  微信昵称（全匹配）
     */
    public function ranking()
    {
        //增加验证场景进行验证
        if (!$this->validate->scene('ranking')->check($this->request->all())) {
            return $this->returnApi(201,  $this->validate->getError());
        }
        $act_info = $this->activityModel->detail($this->request->act_id, null, null);

        if (empty($act_info)) {
            return $this->returnApi(201, '参数错误');
        }

        if ($act_info['node'] == 1 && !empty($this->request->unit_id)) {
            return $this->returnApi(201, '此活动为独立活动，不允许选择单位');
        }
        $cache_key = md5($this->request->token . $this->request->act_id . $this->request->unit_id . $this->request->page . $this->request->limit . $this->request->keywords);
        $cache_rank = Cache::get($cache_key);

        if (empty($cache_rank)) {
            $userInfoModel = new UserInfo();
            $userDrawAddressModel = new UserDrawAddress();
            $activityUserUnitModel = new AnswerActivityUserUnit();

            if ($this->request->keywords) {
                //查询某个用户的排名
                //获取用户排名
                $user_guid = $userInfoModel->getUserGuidByKeywords($this->request->keywords);
                if (empty($user_guid)) {
                    $res['data'] = [];
                } else {
                    $user_rank = $this->model->userRanking($act_info['pattern'], $this->request->act_id, $this->request->unit_id, $user_guid);
                    if (empty($user_rank)) {
                        $res['data'] = [];
                    } else {
                        $user_info = $userInfoModel->getWechatInfo($user_guid);
                        $user_draw_address_info = $userDrawAddressModel->detail($user_guid, $this->request->act_id);
                        $user_address = $activityUserUnitModel->getUserUnitInfo($user_guid, $this->request->act_id);
                        //组装数据
                        $res['data'] = [
                            [
                                'user_guid' => $user_guid,
                                'unit_name' => $activityUserUnitModel->getUnitName($this->request->act_id, $user_guid),
                                'correct_number' => $user_rank['correct_number'],
                                'accuracy' => $user_rank['accuracy'],
                                'create_time' => $user_rank['create_time'],
                                'change_time' => $user_rank['change_time'],
                                'user_wechat_info' => $user_info,
                                'rank' => $user_rank['rank'],
                                'user_draw_address_info' => $user_draw_address_info,
                                'user_unit_info' =>  $user_address
                            ]
                        ];
                    }
                }
            } else {
                $res = $this->model->getRanking($act_info['pattern'], $this->request->act_id, $this->request->unit_id, 9999);

                if (empty($res['data'])) {
                    $res['data'] = [];
                } else {
                    $commonController = new CommonController();
                    foreach ($res['data'] as $key => $val) {
                        $res['data'][$key]['unit_name'] = $activityUserUnitModel->getUnitName($this->request->act_id, $val['user_guid']);
                        $res['data'][$key]['user_wechat_info'] = $userInfoModel->getWechatInfo($val['user_guid']);
                        $res['data'][$key]['rank'] = $commonController->addSerialNumberOne($key, $this->request->page, $this->request->limit);
                        $res['data'][$key]['user_draw_address_info'] = $userDrawAddressModel->detail($val['user_guid'], 1, $this->request->act_id);
                        $res['data'][$key]['user_unit_info'] = $activityUserUnitModel->getUserUnitInfo($val['user_guid'], $this->request->act_id);
                        $res['data'][$key]['times'] = second_to_time($val['times']);
                    }
                }
            }
            Cache::put($cache_key, $res, 6); //缓存一分钟
        } else {
            $res = $cache_rank;
        }

        $row[0]["id"] = '序号';
        $row[0]["rank"] = '排名';
        if ($act_info['node'] != 1) $row[0]["name"] = '所属单位名称';
        $row[0]["nickname"] = '昵称';
        //   $row[0]["tel"] = '电话号码';
        $row[0]["accuracy"] = '正确率';
        $row[0]["correct_number"] = '答题正确数';
        $row[0]["create_time"] = '正确率第一次更新时间';
        $row[0]["change_time"] = '正确率最近一次更新时间';
        $row[0]["take_username"] = '收货姓名';
        $row[0]["take_tel"] = '收货电话号码';
        $row[0]["province"] = '省';
        $row[0]["city"] = '市';
        $row[0]["district"] = '区';
        $row[0]["address"] = '详细地址';

        $answer_activity_gift_type = config('other.answer_activity_gift_type');
        if (in_array(1, $answer_activity_gift_type)) {
            $row[0]["state"] = '是否发放红包';
            $row[0]["price"] = '红包发放金额（元）';
            $row[0]["order_id"] = '发放红包订单号';
            $row[0]["pay_time"] = '发放红包时间';
        }

        $title = '用户排名列表-' . date('YmdHis');

        $data = $this->setData($res['data'], $act_info['node']); //要导入的数据

        return $this->exportData($data, $title, $row);
    }



    /**
     * 导出数据
     *
     * @param [type] $data
     * @return void
     */
    public function exportData($data, $title, $row)
    {
        $header = $row; //导出表头
        $excel = new Export($data, $header, $title);
        $excel->setColumnWidth(['A' => 10, 'B' => 15, 'C' => 20, 'D' => 20, 'E' => 20, 'F' => 20, 'G' => 20, 'H' => 25, 'I' => 25, 'J' => 20, 'K' => 30, 'L' => 20, 'M' => 20, 'N' => 20, 'O' => 30]);
        $excel->setRowHeight([1 => 30]);
        // $excel->setFreezePane('A2');
        // $excel->setFont(['A1:Z1265' => '宋体']);
        // $excel->setFontSize(['A1:I1' => 14,'A2:Z1265' => 10]);
        // $excel->setBold(['A1:Z2' => true]);
        // $excel->setBackground(['A1:A1' => '808080','C1:C1' => '708080']);
        // $excel->setMergeCells(['A1:I1']);
        // $excel->setBorders(['A2:D5' => '#000000']);
        return Excel::download($excel, $title . '.xlsx');
    }


    /**
     * 处理 终端书籍列表 数据
     */
    public function setData($data, $node)
    {

        $excel_data = [];
        /*设置excel内容*/
        foreach ($data as $key => $val) {
            $excel_data[$key]['id'] = $key + 1;
            $excel_data[$key]["rank"] = $val["rank"];
            if ($node != 1) {
                $excel_data[$key]["unit_name"] = $val['unit_name'];
            }
            $excel_data[$key]["nickname"] = $val['user_wechat_info']["nickname"];
            //   $excel_data[$key]["tel"] = $val['user_wechat_info']["tel"];
            $excel_data[$key]["accuracy"] = $val["accuracy"] . '%';
            $excel_data[$key]["correct_number"] = (string)$val["correct_number"];
            $excel_data[$key]["create_time"] = $val["create_time"];
            $excel_data[$key]["change_time"] = $val["change_time"];

            $excel_data[$key]["take_username"] = !empty($val['user_draw_address_info']["username"]) ? $val['user_draw_address_info']["username"] : '';
            $excel_data[$key]["take_tel"] = !empty($val['user_draw_address_info']["tel"]) ? $val['user_draw_address_info']["tel"] . "\t" : '';
            $excel_data[$key]["province"] = !empty($val['user_draw_address_info']["province"]) ? $val['user_draw_address_info']["province"] : '';
            $excel_data[$key]["city"] = !empty($val['user_draw_address_info']["city"]) ? $val['user_draw_address_info']["city"] : '';
            $excel_data[$key]["district"] = !empty($val['user_draw_address_info']["district"]) ? $val['user_draw_address_info']["district"] : '';
            $excel_data[$key]["address"] = !empty($val['user_draw_address_info']["address"]) ? $val['user_draw_address_info']["address"] : '';

            $answer_activity_gift_type = config('other.answer_activity_gift_type');
            if (in_array(1, $answer_activity_gift_type)) {
                $excel_data[$key]["state"] = $this->getSendState($val["state"]);
                $excel_data[$key]["price"] = $val["price"];
                $excel_data[$key]["order_id"] = $val["order_id"];
                $excel_data[$key]["pay_time"] = $val["pay_time"];
            }
        }

        return $excel_data;
    }

    /**
     * 发放红包状态
     */
    public function getSendState($state)
    {
        if ($state == 1) {
            return '已发放';
        } else if ($state == 2) {
            return '发放失败';
        } else if ($state == 3) {
            return '发放中';
        } else {
            return '未发放';
        }
    }
}
